package com.chhuang.ewcrm.api;

import com.chhuang.ewcrm.utils.MyAlert;
import com.chhuang.ewcrm.vo.ResultBean;
import io.reactivex.FlowableSubscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author chhuang
 * @create 2020-10-23-12:20
 */
public abstract class ServiceSubscriber<T> implements FlowableSubscriber<ResultBean<T>> {
    private final Logger logger = LoggerFactory.getLogger(ServiceSubscriber.class);

    private String apiName;
    public ServiceSubscriber(String apiName){
        this.apiName = apiName;
    }

    @Override
    public void onSubscribe(Subscription subscription) {
//        logger.debug("onSubscribe");
        subscription.request(2);
    }

    @Override
    public void onNext(ResultBean<T> tResultBean) {
        logger.debug("onNext:"+ tResultBean.toString());
        if(tResultBean.isSuccess()){
            onHandleSuccess(tResultBean.getData());
        }else {
            onHandleError(tResultBean);
        }
    }

    @Override
    public void onError(Throwable e) {
        logger.error("onError:"+e.getMessage());
        MyAlert.showErrorLater("系统异常",apiName, e.getMessage());
    }

    @Override
    public void onComplete() {
//        logger.debug("onComplete");
    }

    protected abstract void onHandleSuccess(T t);

    protected void onHandleError(ResultBean<T> error) {
        logger.error(error.getMessage());
        MyAlert.showErrorLater("接口请求", apiName, error.getMessage());
    }
}
